package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"myai/core"
	"myai/core/types"
	"myai/store/model"
	"myai/store/model/req"
	"myai/store/vo"
	"myai/utils"
	"myai/utils/resp"
)

type PowerLogHandler struct {
	BaseHandler
}

func NewPowerLogHandler(app *core.AppServer, db *gorm.DB) *PowerLogHandler {
	return &PowerLogHandler{BaseHandler{App: app, DB: db}}
}

// List godoc
// @Summary      获取用户算力日志
// @Description  获取用户算力日志
// @Tags         前台-算力日志
// @Accept       json
// @Produce      json
// @Param        req   body     req.PowerLogListReq  true  "获取用户算力日志参数"
// @Success      200  {object}  types.BizVo{data=vo.Page}
// @Router       /api/powerLog/list [post]
// @Security ApiKeyAuth
func (h *PowerLogHandler) List(c *gin.Context) {
	var data req.PowerLogListReq
	if err := c.ShouldBindJSON(&data); err != nil {
		resp.ERROR(c, types.InvalidArgs)
		return
	}

	session := h.DB.Session(&gorm.Session{})
	userId := h.GetLoginUserId(c)
	session = session.Where("user_id", userId)
	if data.Model != "" {
		session = session.Where("model", data.Model)
	}

	if len(data.Date) == 2 {
		start := data.Date[0] + " 00:00:00"
		end := data.Date[1] + " 23:59:59"
		session = session.Where("created_at >= ? and created_at <= ?", start, end)
	}

	var total int64
	// 查询算力日志数量
	session.Model(&model.PowerLog{}).Count(&total)
	var items []model.PowerLog
	var list = make([]vo.PowerLog, 0)
	offset := (data.Page - 1) * data.PageSize
	res := session.Order("id desc").Offset(offset).Limit(data.PageSize).Find(&items)
	if res.Error == nil {
		for _, v := range items {
			var powerLogVo vo.PowerLog
			err := utils.CopyObject(v, &powerLogVo)
			if err != nil {
				log.Errorf("拷贝数据出现错误：%v", err)
				continue
			}
			powerLogVo.Id = v.Id
			powerLogVo.CreatedAt = v.CreatedAt.Unix()
			powerLogVo.TypeStr = v.Type.String()
			list = append(list, powerLogVo)
		}
	}
	resp.SUCCESS(c, vo.NewPage(total, data.Page, data.PageSize, list))
}
